﻿/* $Author: alexander@bsrgin.ru $
 * $Id: LayoutMainLandscape.java 8 2011-11-13 20:11:06Z alexander@bsrgin.ru $
 * 
 */
package ru.habrahabr.prettyalarm;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class LayoutMainLandscape extends ViewGroup
{
	public LayoutMainLandscape(Context context)
	{
		super(context, null);
	}

	public LayoutMainLandscape(Context context, AttributeSet attrs)
	{
		super(context, attrs, 0);
	}

	public LayoutMainLandscape(Context context, AttributeSet attrs, int defStyle)
	{
		super(context, attrs, defStyle);
	}
	
	private final static double DIMENSION_CURR_TIME_HEIGHT = 100.0 / 160.0;

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b)
	{
		final int width = getWidth();
		final int height = getHeight();
		final int count = getChildCount();

		TextView txtCurrent = null;
		TextView txtLeft = null;
		
		for (int i = 0; i < count; i++)
		{
			View v = getChildAt(i);
			switch (v.getId())
			{
			case R.id.main_current_time: txtCurrent = (TextView)v; break; 
			case R.id.main_left_time: txtLeft = (TextView)v; break; 
			}
		}
		
		// 23:15
		final int curr_time_height = (int)(height * DIMENSION_CURR_TIME_HEIGHT);
		txtCurrent.measure(
				MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
				MeasureSpec.makeMeasureSpec(curr_time_height, MeasureSpec.EXACTLY));
		txtCurrent.layout(0, 0, width, curr_time_height);
		adjustTextBounds(txtCurrent, 80, width, curr_time_height);
		// вставать через 7 часов
		final int left_time_offset = curr_time_height;
		txtLeft.measure(
				MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
				MeasureSpec.makeMeasureSpec(curr_time_height, MeasureSpec.EXACTLY));
		txtLeft.layout(0, left_time_offset, width, height);
		adjustTextBounds(txtLeft, 120, width, height-curr_time_height);
	}

	// см. http://www.pushing-pixels.org/2010/12/16/meet-the-green-goblin-part-4.html
	// см. http://android-argentina.blogspot.com/2011/01/resizablebutton.html
	private void adjustTextBounds(TextView tv, float max_text_size, int max_width, int max_height)
	{
		int newWidth, newHeight;
		float size = max_text_size;
		do {
			tv.setTextSize(size--);
			tv.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
			newWidth = tv.getMeasuredWidth();
			newHeight = tv.getMeasuredHeight();
		} while (newWidth > max_width || newHeight > max_height);
	}
}
